<template>
    <div class="profile-view">
        <div class="page-header">
            <h1>个人中心</h1>
            <p>管理您的个人信息</p>
        </div>

        <el-card class="profile-card">
            <el-tabs v-model="activeTab">
                <el-tab-pane label="基本信息" name="info">
                    <div class="tab-content">
                        <el-form :model="profileForm" label-width="80px">
                            <el-form-item label="用户名">
                                <el-input v-model="profileForm.username" disabled />
                            </el-form-item>
                            <el-form-item label="昵称">
                                <el-input v-model="profileForm.nickname" />
                            </el-form-item>
                            <el-form-item label="邮箱">
                                <el-input v-model="profileForm.email" disabled />
                            </el-form-item>
                            <el-form-item label="手机号">
                                <el-input v-model="profileForm.phone" disabled />
                            </el-form-item>
                            <el-form-item>
                                <el-button type="primary" @click="updateProfile" :loading="updating">保存</el-button>
                            </el-form-item>
                        </el-form>
                    </div>
                </el-tab-pane>
                <el-tab-pane label="修改密码" name="password">
                    <div class="tab-content">
                        <el-form :model="passwordForm" :rules="passwordRules" ref="passwordFormRef" label-width="100px">
                            <el-form-item label="当前密码" prop="oldPassword">
                                <el-input type="password" v-model="passwordForm.oldPassword" show-password />
                            </el-form-item>
                            <el-form-item label="新密码" prop="newPassword">
                                <el-input type="password" v-model="passwordForm.newPassword" show-password />
                            </el-form-item>
                            <el-form-item label="确认新密码" prop="confirmPassword">
                                <el-input type="password" v-model="passwordForm.confirmPassword" show-password />
                            </el-form-item>
                            <el-form-item>
                                <el-button type="primary" @click="changePassword" :loading="changingPassword">修改密码</el-button>
                            </el-form-item>
                        </el-form>
                    </div>
                </el-tab-pane>
            </el-tabs>
        </el-card>
    </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { useUserStore } from '@/stores/user'
import { ElMessage, type FormInstance, type FormRules } from 'element-plus'
import { updateUserProfile, changePassword as changePasswordApi } from '@/api/modules/user'

const userStore = useUserStore()

const activeTab = ref('info')
const updating = ref(false)
const changingPassword = ref(false)

const profileForm = reactive({
    username: '',
    nickname: '',
    email: '',
    phone: '',
})

const passwordForm = reactive({
    oldPassword: '',
    newPassword: '',
    confirmPassword: '',
})

const passwordFormRef = ref<FormInstance>()

const passwordRules: FormRules = {
    oldPassword: [{ required: true, message: '请输入当前密码', trigger: 'blur' }],
    newPassword: [
        { required: true, message: '请输入新密码', trigger: 'blur' },
        { min: 6, message: '密码长度不能少于6位', trigger: 'blur' },
    ],
    confirmPassword: [
        { required: true, message: '请确认新密码', trigger: 'blur' },
        {
            validator: (rule, value, callback) => {
                if (value !== passwordForm.newPassword) {
                    callback(new Error('两次输入的密码不一致'))
                } else {
                    callback()
                }
            },
            trigger: 'blur',
        },
    ],
}

const loadProfile = () => {
    if (userStore.user) {
        profileForm.username = userStore.user.username
        profileForm.nickname = userStore.user.nickname || ''
        profileForm.email = userStore.user.email
        profileForm.phone = userStore.user.phone
    }
}

const updateProfile = async () => {
    try {
        updating.value = true
        await updateUserProfile({ nickname: profileForm.nickname })
        await userStore.initUserState()
        ElMessage.success('个人信息更新成功')
    } catch (error) {
        console.error('更新个人信息失败:', error)
        ElMessage.error('更新失败，请重试')
    } finally {
        updating.value = false
    }
}

const changePassword = async () => {
    // TODO: Implement change password functionality in the backend
    if (!passwordFormRef.value) return
    await passwordFormRef.value.validate(async (valid) => {
        if (valid) {
            try {
                changingPassword.value = true
                await changePasswordApi(passwordForm)
                ElMessage.success('密码修改成功')
                passwordForm.oldPassword = ''
                passwordForm.newPassword = ''
                passwordForm.confirmPassword = ''
            } catch (error) {
                console.error('修改密码失败:', error)
                ElMessage.error('修改密码失败，请重试')
            } finally {
                changingPassword.value = false
            }
        }
    })
}

onMounted(() => {
    loadProfile()
})
</script>

<style scoped>
.profile-view {
    max-width: 800px;
    margin: 0 auto;
    padding: 20px;
}

.page-header {
    text-align: center;
    margin-bottom: 30px;
}

.page-header h1 {
    color: #333;
    margin-bottom: 10px;
    font-size: 28px;
    font-weight: 600;
}

.page-header p {
    color: #666;
    font-size: 16px;
}

.profile-card {
    border-radius: 8px;
}

.tab-content {
    padding: 20px;
}
</style>
